package com.dinnerorders.web.windows.login;

import com.dinnerorders.common.models.User;
import com.dinnerorders.common.services.LdapService;
import com.dinnerorders.common.services.UserService;
import com.dinnerorders.web.DinnerordersApplication;
import com.dinnerorders.web.enums.MessageCode;
import com.dinnerorders.web.helpers.MessageHelper;
import com.dinnerorders.web.windows.MainWindow;
import com.vaadin.server.Page;
import com.vaadin.ui.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Qualifier;

@Configurable(preConstruction = true)
public class LoginForm extends VerticalLayout {

    @Autowired
    @Qualifier(value = "ldapService")
    private LdapService ldapService;

    @Autowired
    @Qualifier(value = "userService")
    private UserService userService;

    private TextField loginField;
    private PasswordField passwordField;
    private Button loginButton;

    public LoginForm() {
        super();
        initComponents();
        addComponentsToForm();
    }

    private void initComponents() {
        loginField = new TextField(MessageHelper.getMessage(MessageCode.LOGIN_FORM_LOGIN));
        passwordField = new PasswordField(MessageHelper.getMessage(MessageCode.LOGIN_FORM_PASSWORD));
        loginButton = new Button(MessageHelper.getMessage(MessageCode.LOGIN_FORM_BTN_LOGIN));
        loginButton.addClickListener(getLoginListener());
    }

    private void addComponentsToForm() {
        addComponent(loginField);
        addComponent(passwordField);
        addComponent(loginButton);
    }

    public Button.ClickListener getLoginListener() {
        return new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                String login = loginField.getValue();
                String password = passwordField.getValue();
                if (ldapService.checkUser(login, password)) {
                    User user = userService.findUserByLdapLogin(login);
                    ((DinnerordersApplication) getUI()).setActiveUser(user);
                    UI.getCurrent().addWindow(new MainWindow());

                } else {
                    Notification notification = new Notification(
                            MessageHelper.getMessage(MessageCode.COMMON_ERROR),
                            MessageHelper.getMessage(MessageCode.INCORRECT_USERNAME_OR_PASSWORD),
                            Notification.Type.ERROR_MESSAGE);
                    notification.show(Page.getCurrent());
                }
            }
        };
    }
}
